package com.lyh.notes.task.email;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lyh.notes.model.enums.RedisKey;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.mail.internet.MimeMessage;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class EmailTaskConsumer {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    private JavaMailSender mailSender;

    @Autowired
    private TemplateEngine templateEngine;

    @Autowired
    private ObjectMapper objectMapper;

    @Value("${spring.mail.username}")
    private String from;


    @Scheduled(fixedRate = 3000)
    public void consumeEmailTask() throws JsonProcessingException {
        String taskKey= RedisKey.emailTaskQueue();
        while(true){
            //1.取出任务的json字符串
            String taskJson=redisTemplate.opsForList().rightPop(taskKey);
            if(taskJson==null){
                break;
            }
            // 2.将字符串解析成emailTask
            EmailTask emailTask=objectMapper.readValue(taskJson, EmailTask.class);
            taskJson = taskJson.replaceAll("^\"|\"$", "").replace("\\\"", "\"");
            // 3.发送任务
            String receiver=emailTask.getEmail();
            String verificationCode=emailTask.getCode();
            try {
                Context context=new Context();
                context.setVariable("verifyCode",verificationCode);
                context.setVariable("operationType","注册");
                String emailContent= templateEngine.process("/email/verify-code",context);

                MimeMessage mimeMessage = mailSender.createMimeMessage();
                MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true,"UTF-8");
                helper.setFrom(from);
                helper.setTo(receiver);
                // 设置邮件主题
                helper.setSubject("YH-NOTE验证码");
                // 设置邮件正文，并且第二个参数true表示这是一个HTML邮件
                helper.setText(emailContent, true);
                mailSender.send(mimeMessage);
                // 4.保存验证码到redis
                redisTemplate.opsForValue().set(RedisKey.registerVerificationCode(receiver),verificationCode,5, TimeUnit.MINUTES);

            } catch (Exception e) {
                log.error("邮件发送失败", e);
            }

        }
    }
}
